<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>7. 输入和输出 &mdash; Python tutorial 3.4 documentation</title>
    
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    './',
        VERSION:     '3.4',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <link rel="top" title="Python tutorial 3.4 documentation" href="index.html" />
    <link rel="next" title="8. 错误和异常" href="errors.html" />
    <link rel="prev" title="6. 模块" href="modules.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="errors.html" title="8. 错误和异常"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="modules.html" title="6. 模块"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">Python tutorial 3.4 documentation</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="tut-io">
<span id="id1"></span><h1>7. 输入和输出<a class="headerlink" href="#tut-io" title="Permalink to this headline">¶</a></h1>
<p>一个程序可以有几种输出方式：以人类可读的方式打印数据，或者写入一个文件供以后使用。 本章将讨论几种可能性。</p>
<div class="section" id="tut-formatting">
<span id="id2"></span><h2>7.1. 格式化输出<a class="headerlink" href="#tut-formatting" title="Permalink to this headline">¶</a></h2>
<p>我们有两种大相径庭地输出值方法：表达式语句 和 <tt class="xref py py-func docutils literal"><span class="pre">print()</span></tt> 函数。（第三种访求是使用文件对象的 <tt class="xref py py-meth docutils literal"><span class="pre">write()</span></tt> 方法，标准文件输出可以参考 <tt class="docutils literal"><span class="pre">sys.stdout</span></tt> 。详细内容参见库参考手册。）</p>
<p>通常，你想要对输出做更多的格式控制，而不是简单的打印使用空格分隔的值。 有两种方法可以格式化你的输出： 第一种方法是由你自己处理整个字符串，通过使用字符串切割和连接操作可以创建任何你想要的输出形式。string 类型包含一些将字符串填充到指定列宽度的有用操作，随后就会讨论这些。 第二种方法是使用 <tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt> 方法。</p>
<p>标准模块 <tt class="xref py py-mod docutils literal"><span class="pre">string</span></tt> 包括了一些操作，将字符串填充入给定列时，这些操作很有用。随后我们会讨论这部分内容。第二种方法是使用 <tt class="xref py py-class docutils literal"><span class="pre">Template</span></tt> 方法。</p>
<p>当然，还有一个问题，如何将值转化为字符串？很幸运，Python 有办法将任意值转为字符串：将它传入 <tt class="xref py py-func docutils literal"><span class="pre">repr()</span></tt> 或 <tt class="xref py py-func docutils literal"><span class="pre">str()</span></tt> 函数。</p>
<p>函数 <tt class="xref py py-func docutils literal"><span class="pre">str()</span></tt> 用于将值转化为适于人阅读的形式，而 <tt class="xref py py-func docutils literal"><span class="pre">repr()</span></tt> 转化为供解释器读取的形式（如果没有等价的语法，则会发生 <tt class="xref py py-exc docutils literal"><span class="pre">SyntaxError</span></tt> 异常） 某对象没有适于人阅读的解释形式的话， <tt class="xref py py-func docutils literal"><span class="pre">str()</span></tt> 会返回与 <tt class="xref py py-func docutils literal"><span class="pre">repr()</span></tt> 等同的值。很多类型，诸如数值或链表、字典这样的结构，针对各函数都有着统一的解读方式。字符串和浮点数，有着独特的解读方式。</p>
<p>下面有些例子:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s">&#39;Hello, world.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">&#39;Hello, world.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">repr</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">&quot;&#39;Hello, world.&#39;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="mi">1</span><span class="o">/</span><span class="mi">7</span><span class="p">)</span>
<span class="go">&#39;0.14285714285714285&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span> <span class="o">*</span> <span class="mf">3.25</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="mi">200</span> <span class="o">*</span> <span class="mi">200</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s">&#39;The value of x is &#39;</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">+</span> <span class="s">&#39;, and y is &#39;</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="n">y</span><span class="p">)</span> <span class="o">+</span> <span class="s">&#39;...&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">The value of x is 32.5, and y is 40000...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># The repr() of a string adds string quotes and backslashes:</span>
<span class="gp">... </span><span class="n">hello</span> <span class="o">=</span> <span class="s">&#39;hello, world</span><span class="se">\n</span><span class="s">&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">hellos</span> <span class="o">=</span> <span class="nb">repr</span><span class="p">(</span><span class="n">hello</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="n">hellos</span><span class="p">)</span>
<span class="go">&#39;hello, world\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># The argument to repr() may be any Python object:</span>
<span class="gp">... </span><span class="nb">repr</span><span class="p">((</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="p">(</span><span class="s">&#39;spam&#39;</span><span class="p">,</span> <span class="s">&#39;eggs&#39;</span><span class="p">)))</span>
<span class="go">&quot;(32.5, 40000, (&#39;spam&#39;, &#39;eggs&#39;))&quot;</span>
</pre></div>
</div>
<p>有两种方式可以写平方和立方表:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">3</span><span class="p">),</span> <span class="n">end</span><span class="o">=</span><span class="s">&#39; &#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="c"># Note use of &#39;end&#39; on previous line</span>
<span class="gp">... </span>    <span class="k">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">4</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go"> 1   1    1</span>
<span class="go"> 2   4    8</span>
<span class="go"> 3   9   27</span>
<span class="go"> 4  16   64</span>
<span class="go"> 5  25  125</span>
<span class="go"> 6  36  216</span>
<span class="go"> 7  49  343</span>
<span class="go"> 8  64  512</span>
<span class="go"> 9  81  729</span>
<span class="go">10 100 1000</span>

<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">print</span><span class="p">(</span><span class="s">&#39;{0:2d} {1:3d} {2:4d}&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go"> 1   1    1</span>
<span class="go"> 2   4    8</span>
<span class="go"> 3   9   27</span>
<span class="go"> 4  16   64</span>
<span class="go"> 5  25  125</span>
<span class="go"> 6  36  216</span>
<span class="go"> 7  49  343</span>
<span class="go"> 8  64  512</span>
<span class="go"> 9  81  729</span>
<span class="go">10 100 1000</span>
</pre></div>
</div>
<p>(注意第一个例子， <tt class="xref std std-keyword docutils literal"><span class="pre">print</span></tt> 在每列之间加了一个空格，它总是在参数间加入空格。)</p>
<p>以上是一个 <tt class="xref py py-meth docutils literal"><span class="pre">str.rjust()</span></tt> 方法的演示，它把字符串输出到一列，并通过向左侧填充空格来使其右对齐。类似的方法还有 <tt class="xref py py-meth docutils literal"><span class="pre">str.ljust()</span></tt> 和 <tt class="xref py py-meth docutils literal"><span class="pre">str.center()</span></tt> 。这些函数只是输出新的字符串，并不改变什么。如果输出的字符串太长，它们也不会截断它，而是原样输出，这会使你的输出格式变得混乱，不过总强过另一种选择（截断字符串），因为那样会产生错误的输出值。（如果你确实需要截断它，可以使用切割操作，例如： <tt class="docutils literal"><span class="pre">x.ljust(n)[:n]</span></tt> 。）</p>
<p>还有另一个方法， <tt class="xref py py-meth docutils literal"><span class="pre">str.zfill()</span></tt> 它用于向数值的字符串表达左侧填充 0。该函数可以正确理解正负号:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;12&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="go">&#39;00012&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;-3.14&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="go">&#39;-003.14&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;3.14159265359&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="go">&#39;3.14159265359&#39;</span>
</pre></div>
</div>
<p>方法 <tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt> 的基本用法如下:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="s">&#39;We are the {} who say &quot;{}!&quot;&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s">&#39;knights&#39;</span><span class="p">,</span> <span class="s">&#39;Ni&#39;</span><span class="p">))</span>
<span class="go">We are the knights who say &quot;Ni!&quot;</span>
</pre></div>
</div>
<p>大括号和其中的字符会被替换成传入 <tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt> 的参数。大括号中的数值指明使用传入 <tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt> 方法的对象中的哪一个。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="s">&#39;{0} and {1}&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s">&#39;spam&#39;</span><span class="p">,</span> <span class="s">&#39;eggs&#39;</span><span class="p">))</span>
<span class="go">spam and eggs</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="s">&#39;{1} and {0}&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s">&#39;spam&#39;</span><span class="p">,</span> <span class="s">&#39;eggs&#39;</span><span class="p">))</span>
<span class="go">eggs and spam</span>
</pre></div>
</div>
<p>如果在 <tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt> 调用时使用关键字参数，可以通过参数名来引用值。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="s">&#39;This {food} is {adjective}.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
<span class="gp">... </span>      <span class="n">food</span><span class="o">=</span><span class="s">&#39;spam&#39;</span><span class="p">,</span> <span class="n">adjective</span><span class="o">=</span><span class="s">&#39;absolutely horrible&#39;</span><span class="p">))</span>
<span class="go">This spam is absolutely horrible.</span>
</pre></div>
</div>
<p>定位和关键字参数可以组合使用:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="s">&#39;The story of {0}, {1}, and {other}.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s">&#39;Bill&#39;</span><span class="p">,</span> <span class="s">&#39;Manfred&#39;</span><span class="p">,</span>
<span class="go">                                                       other=&#39;Georg&#39;))</span>
<span class="go">The story of Bill, Manfred, and Georg.</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">'!a'</span></tt> (应用 <tt class="xref py py-func docutils literal"><span class="pre">ascii()</span></tt>), <tt class="docutils literal"><span class="pre">'!s'</span></tt> （应用 <tt class="xref py py-func docutils literal"><span class="pre">str()</span></tt> ） 和 <tt class="docutils literal"><span class="pre">'!r'</span></tt> （应用 <tt class="xref py py-func docutils literal"><span class="pre">repr()</span></tt> ） 可以在格式化之前转换值:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="s">&#39;The value of PI is approximately {}.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">))</span>
<span class="go">The value of PI is approximately 3.14159265359.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="s">&#39;The value of PI is approximately {!r}.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">))</span>
<span class="go">The value of PI is approximately 3.141592653589793.</span>
</pre></div>
</div>
<p>字段名后允许可选的 <tt class="docutils literal"><span class="pre">':'</span></tt> 和格式指令。这允许对值的格式化加以更深入的控制。下例将 Pi 转为三位精度。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="s">&#39;The value of PI is approximately {0:.3f}.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">))</span>
<span class="go">The value of PI is approximately 3.142.</span>
</pre></div>
</div>
<p>在字段后的 <tt class="docutils literal"><span class="pre">':'</span></tt> 后面加一个整数会限定该字段的最小宽度，这在美化表格时很有用。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s">&#39;Sjoerd&#39;</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s">&#39;Jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s">&#39;Dcab&#39;</span><span class="p">:</span> <span class="mi">7678</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">name</span><span class="p">,</span> <span class="n">phone</span> <span class="ow">in</span> <span class="n">table</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="gp">... </span>    <span class="k">print</span><span class="p">(</span><span class="s">&#39;{0:10} ==&gt; {1:10d}&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">phone</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go">Jack       ==&gt;       4098</span>
<span class="go">Dcab       ==&gt;       7678</span>
<span class="go">Sjoerd     ==&gt;       4127</span>
</pre></div>
</div>
<p>如果你有个实在是很长的格式化字符串，不想分割它。如果你可以用命名来引用被格式化的变量而不是位置就好了。有个简单的方法，可以传入一个字典，用中括号访问它的键:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s">&#39;Sjoerd&#39;</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s">&#39;Jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s">&#39;Dcab&#39;</span><span class="p">:</span> <span class="mi">8637678</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="s">&#39;Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; &#39;</span>
<span class="go">          &#39;Dcab: {0[Dcab]:d}&#39;.format(table))</span>
<span class="go">Jack: 4098; Sjoerd: 4127; Dcab: 8637678</span>
</pre></div>
</div>
<p>也可以用 ‘**’ 标志将这个字典以关键字参数的方式传入。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s">&#39;Sjoerd&#39;</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s">&#39;Jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s">&#39;Dcab&#39;</span><span class="p">:</span> <span class="mi">8637678</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="s">&#39;Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">**</span><span class="n">table</span><span class="p">))</span>
<span class="go">Jack: 4098; Sjoerd: 4127; Dcab: 8637678</span>
</pre></div>
</div>
<p>这种方式与新的内置函数 <tt class="xref py py-func docutils literal"><span class="pre">vars()</span></tt> 组合使用非常有效。该函数返回包含所有局部变量的字典。</p>
<p>要进一步了解字符串格式化方法 <tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt> ，参见 <em class="xref std std-ref">formatstrings</em> 。</p>
<div class="section" id="id3">
<h3>7.1.1. 旧式的字符串格式化<a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h3>
<p>操作符 <tt class="docutils literal"><span class="pre">%</span></tt> 也可以用于字符串格式化。它以类似 <tt class="xref c c-func docutils literal"><span class="pre">sprintf()</span></tt>-style 的方式解析左参数，将右参数应用于此，得到格式化操作生成的字符串，例如:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="s">&#39;The value of PI is approximately </span><span class="si">%5.3f</span><span class="s">.&#39;</span> <span class="o">%</span> <span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">)</span>
<span class="go">The value of PI is approximately 3.142.</span>
</pre></div>
</div>
<p>因为 <tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt> 还很新，大量 Python 代码还在使用 % 操作符。然而，因为旧式的格式化方法最终将从语言中去掉，应该尽量使用　<tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt> 。</p>
<p>进一步的信息可以参见　<em class="xref std std-ref">string-formatting</em> 一节。</p>
</div>
</div>
<div class="section" id="tut-files">
<span id="id4"></span><h2>7.2. 文件读写<a class="headerlink" href="#tut-files" title="Permalink to this headline">¶</a></h2>
<p id="index-0">函数 <tt class="xref py py-func docutils literal"><span class="pre">open()</span></tt> 返回文件对象，通常的用法需要两个参数： <tt class="docutils literal"><span class="pre">open(filename,</span> <span class="pre">mode)</span></tt>。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s">&#39;/tmp/workfile&#39;</span><span class="p">,</span> <span class="s">&#39;w&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>第一个参数是一个标识文件名的字符串。第二个参数是由有限的字母组成的字符串，描述了文件将会被如何使用。可选的 <em>模式</em> 有： <tt class="docutils literal"><span class="pre">'r'</span></tt> ，此选项使文件只读； <tt class="docutils literal"><span class="pre">'w'</span></tt> ，此选项使文件只写（对于同名文件，该操作使原有文件被覆盖）； <tt class="docutils literal"><span class="pre">'a'</span></tt> ，此选项以追加方式打开文件； <tt class="docutils literal"><span class="pre">'r+'</span></tt> ，此选项以读写方式打开文件； 模式 参数是可选的。如果没有指定，默认为 <tt class="docutils literal"><span class="pre">'r'</span></tt> 模式。</p>
<p>在 Windows 平台上， <tt class="docutils literal"><span class="pre">'b'</span></tt> 模式以二进制方式打开文件，所以可能会有类似于 <tt class="docutils literal"><span class="pre">'rb'</span></tt> ， <tt class="docutils literal"><span class="pre">'wb'</span></tt> ， <tt class="docutils literal"><span class="pre">'r+b'</span></tt> 等等模式组合。Windows 平台上文本文件与二进制文件是有区别的，读写文本文件时，行尾会自动添加行结束符。这种后台操作方式对 ASCII 文本文件没有什么问题，但是操作 <tt class="file docutils literal"><span class="pre">JPEG</span></tt> 或 <tt class="file docutils literal"><span class="pre">EXE</span></tt> 这样的二进制文件时就会产生破坏。在操作这些文件时一定要记得以二进制模式打开。在 Unix 上，加一个 <tt class="docutils literal"><span class="pre">'b'</span></tt> 模式也一样是无害的，所以你可以一切二进制文件处理中平台无关的使用它。</p>
<div class="section" id="tut-filemethods">
<span id="id5"></span><h3>7.2.1. 文件对象方法<a class="headerlink" href="#tut-filemethods" title="Permalink to this headline">¶</a></h3>
<p>本节中的示例都默认文件对象 <tt class="docutils literal"><span class="pre">f</span></tt> 已经创建。</p>
<p>要读取文件内容，需要调用 <tt class="docutils literal"><span class="pre">f.read(size)</span></tt> ，该方法读取若干数量的数据并以字符串形式返回其内容， <em>size</em> 是可选的数值，指定字符串长度。如果没有指定 <em>size</em> 或者指定为负数，就会读取并返回整个文件。当文件大小为当前机器内存两倍时，就会产生问题。反之，会尽可能按比较大的 <em>size</em> 读取和返回数据。如果到了文件末尾，<tt class="docutils literal"><span class="pre">f.read()</span></tt> 会返回一个空字符串（<tt class="docutils literal"><span class="pre">”“</span></tt>）。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="go">&#39;This is the entire file.\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="go">&#39;&#39;</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">f.readline()</span></tt> 从文件中读取单独一行，字符串结尾会自动加上一个换行符（ <tt class="docutils literal"><span class="pre">\n</span></tt> ），只有当文件最后一行没有以换行符结尾时，这一操作才会被忽略。这样返回值就不会有混淆，如果如果 <tt class="docutils literal"><span class="pre">f.readline()</span></tt> 返回一个空字符串，那就表示到达了文件末尾，如果是一个空行，就会描述为 <tt class="docutils literal"><span class="pre">'\n'</span></tt> ，一个只包含换行符的字符串。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;This is the first line of the file.\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;Second line of the file\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;&#39;</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">f.readlines()</span></tt> 返回一个列表，其中包含了文件中所有的数据行。如果给定了 <em>sizehint</em> 参数，就会读入多于一行的比特数，从中返回多行文本。这个功能通常用于高效读取大型行文件，避免了将整个文件读入内存。这种操作只返回完整的行。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">readlines</span><span class="p">()</span>
<span class="go">[&#39;This is the first line of the file.\n&#39;, &#39;Second line of the file\n&#39;]</span>
</pre></div>
</div>
<p>一种替代的方法是通过遍历文件对象来读取文件行。 这是一种内存高效、快速，并且代码简介的方式:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">print</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s">&#39;&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">This is the first line of the file.</span>
<span class="go">Second line of the file</span>
</pre></div>
</div>
<p>虽然这种替代方法更简单，但并不具备细节控制能力。 因为这两种方法处理行缓存的方式不同，千万不能搞混。</p>
<p><tt class="docutils literal"><span class="pre">f.write(string)</span></tt> 方法将 string 的内容写入文件，并返回写入字符的长度。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s">&#39;This is a test</span><span class="se">\n</span><span class="s">&#39;</span><span class="p">)</span>
<span class="go">15</span>
</pre></div>
</div>
<p>想要写入其他非字符串内容，首先要将它转换为字符串:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">value</span> <span class="o">=</span> <span class="p">(</span><span class="s">&#39;the answer&#39;</span><span class="p">,</span> <span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">18</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">f.tell()</span></tt> 返回一个整数，代表文件对象在文件中的指针位置，该数值计量了自文件开头到指针处的比特数。需要改变文件对象指针话话，使用 <tt class="docutils literal"><span class="pre">f.seek(offset,from_what)</span></tt> 。指针在该操作中从指定的引用位置移动 <em>offset</em> 比特，引用位置由 <em>from_what</em> 参数指定。 <em>from_what</em> 值为 0 表示自文件起始处开始，1 表示自当前文件指针位置开始，2 表示自文件末尾开始。 <em>from_what</em> 可以忽略，其默认值为零，此时从文件头开始。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s">&#39;/tmp/workfile&#39;</span><span class="p">,</span> <span class="s">&#39;rb+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;0123456789abcdef&#39;</span><span class="p">)</span>
<span class="go">16</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>     <span class="c"># Go to the 6th byte in the file</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">b&#39;5&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="o">-</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="c"># Go to the 3rd byte before the end</span>
<span class="go">13</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">b&#39;d&#39;</span>
</pre></div>
</div>
<p>在文本文件中（那些没有使用 <tt class="docutils literal"><span class="pre">b</span></tt> 模式选项打开的文件），只允许从文件头开始计算相对位置（使用 <tt class="docutils literal"><span class="pre">seek(0,</span> <span class="pre">2)</span></tt>  从文件尾计算时就会引发异常）。</p>
<p>当你使用完一个文件时，调用 <tt class="docutils literal"><span class="pre">f.close()</span></tt> 方法就可以关闭它并释放其占用的所有系统资源。 在调用 <tt class="docutils literal"><span class="pre">f.close()</span></tt> 方法后，试图再次使用文件对象将会自动失败。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
<span class="gr">ValueError</span>: <span class="n">I/O operation on closed file</span>
</pre></div>
</div>
<p>用关键字 <tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt>  处理文件对象是个好习惯。它的先进之处在于文件用完后会自动关闭，就算发生异常也没关系。它是 <tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt>-<tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt> 块的简写:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">&#39;/tmp/workfile&#39;</span><span class="p">,</span> <span class="s">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">read_data</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">closed</span>
<span class="go">True</span>
</pre></div>
</div>
<p>文件对象还有一些不太常用的附加方法，比如 <tt class="xref py py-meth docutils literal"><span class="pre">isatty()</span></tt> 和 <tt class="xref py py-meth docutils literal"><span class="pre">truncate()</span></tt> 在库参考手册中有文件对象的完整指南。</p>
</div>
<div class="section" id="pickle">
<span id="tut-pickle"></span><h3>7.2.2. <tt class="xref py py-mod docutils literal"><span class="pre">pickle</span></tt> 模块<a class="headerlink" href="#pickle" title="Permalink to this headline">¶</a></h3>
<p id="index-1">我们可以很容易的读写文件中的字符串。数值就要多费点儿周折，因为 <tt class="xref py py-meth docutils literal"><span class="pre">read()</span></tt> 方法只会返回字符串，应该将其传入 <tt class="xref py py-func docutils literal"><span class="pre">int()</span></tt> 这样的方法中，就可以将 <tt class="docutils literal"><span class="pre">'123'</span></tt> 这样的字符转为对应的数值 123。不过，当你需要保存更为复杂的数据类型，例如列表、字典，类的实例，事情就会变得更复杂了。</p>
<p>好在用户不必要非得自己编写和调试保存复杂数据类型的代码。 Python 提供了一个名为 <tt class="xref py py-mod docutils literal"><span class="pre">pickle</span></tt> 的标准模块。这是一个令人赞叹的模块，几乎可以把任何 Python 对象 （甚至是一些 Python 代码段！）表达为为字符串，这一过程称之为封装 （ <em class="dfn">pickling</em> ）。从字符串表达出重新构造对象称之为拆封（ <em class="dfn">unpickling</em> ）。封装状态中的对象可以存储在文件或对象中，也可以通过网络在远程的机器之间传输。</p>
<p>如果你有一个对象 <tt class="docutils literal"><span class="pre">x</span></tt> ，一个以写模式打开的文件对象 <tt class="docutils literal"><span class="pre">f</span></tt> ，封装对象的最简单的方法只需要一行代码:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">pickle</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">f</span><span class="p">)</span>
</pre></div>
</div>
<p>如果 <tt class="docutils literal"><span class="pre">f</span></tt> 是一个以读模式打开的文件对象，就可以重装拆封这个对象:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">x</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
</pre></div>
</div>
<p>（如果不想把封装的数据写入文件，这里还有一些其它的变化可用。完整的 <tt class="xref py py-mod docutils literal"><span class="pre">pickle</span></tt> 文档请见Python 库参考手册）。</p>
<p><tt class="xref py py-mod docutils literal"><span class="pre">pickle</span></tt> 是存储 Python 对象以供其它程序或其本身以后调用的标准方法。提供这一组技术的是一个 持久化 对象（ <em class="dfn">persistent</em> object ）。因为 <tt class="xref py py-mod docutils literal"><span class="pre">pickle</span></tt> 的用途很广泛，很多 Python 扩展的作者都非常注意类似矩阵这样的新数据类型是否适合封装和拆封。</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="index.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">7. 输入和输出</a><ul>
<li><a class="reference internal" href="#tut-formatting">7.1. 格式化输出</a><ul>
<li><a class="reference internal" href="#id3">7.1.1. 旧式的字符串格式化</a></li>
</ul>
</li>
<li><a class="reference internal" href="#tut-files">7.2. 文件读写</a><ul>
<li><a class="reference internal" href="#tut-filemethods">7.2.1. 文件对象方法</a></li>
<li><a class="reference internal" href="#pickle">7.2.2. <tt class="docutils literal"><span class="pre">pickle</span></tt> 模块</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="modules.html"
                        title="previous chapter">6. 模块</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="errors.html"
                        title="next chapter">8. 错误和异常</a></p>
  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="_sources/inputoutput.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="errors.html" title="8. 错误和异常"
             >next</a> |</li>
        <li class="right" >
          <a href="modules.html" title="6. 模块"
             >previous</a> |</li>
        <li><a href="index.html">Python tutorial 3.4 documentation</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
        &copy; Copyright 2013, D.D.
      Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.1.
    </div>
  </body>
</html>